package com.igd.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.commons.lang3.StringUtils;

import com.igd.pojo.vo.ComboxData;

 /**
 * @version  1.0
 *
 * @author   QIAOYU
 *
 * @date     2013-6-17
 *
 * @description	 资源文件公共基础类,可获取classpath下的ResourceBundle与获取绝对路径下的资源文件
 */

public class PropertiesUtil {
	
	private static PropertiesUtil putil = null;
	
	private PropertiesUtil(){};
	
	public static PropertiesUtil getInstance(){
		
		if(null == putil){
			
			synchronized (PropertiesUtil.class) {
				
				putil = new PropertiesUtil();

			}
		}
		
		return putil;
	}
	
	/**
	 * 获取资源文件ResourceBundle,此方法仅能获取classpath路径下的文件
	 * 
	 * @param filePath 仅需传入classpath下的文件名称
	 * 
	 * @return ResourceBundle
	 */
	public ResourceBundle getResourceBundle(String fileName){
		
		if(StringUtils.isNotEmpty(fileName)){
			
			return ResourceBundle.getBundle(fileName);
			
		}
		
		return null;
	}
	
	/**
	 * 获取物理路径的资源文件,此方法可获取任意资源文件
	 * 
	 * @param filePath 传入的是绝对路径地址,例如c://conf/conf.properties
	 * 
	 * @return Properties
	 * 
	 * @throws FileNotFoundException
	 * 
	 * @throws IOException
	 */
	public Properties getProperties(String filePath) throws FileNotFoundException, IOException{

		if(StringUtils.isNotEmpty(filePath)){
			
			Properties p = new Properties();
			
			p.load(new FileInputStream(new File(filePath)));
			
			return p;

		}
		
		return null;
	}
	
	/**
	 * 根据传入的类型去获取对应Key的值
	 * 
	 * @param o ResourceBundle or Properties
	 * 
	 * @param key
	 * 
	 * @return ComboxData
	 */
	public ComboxData getVal(Object o,String key){

		if(null != o && StringUtils.isNotEmpty(key)){
			
			if(o instanceof ResourceBundle){
				
				String val =((ResourceBundle) o).getString(key);
				
				return new ComboxData(key,val);

			}else if(o instanceof Properties){
				
				String val = ((Properties) o).getProperty(key);
				
				return new ComboxData(key,val); 

			}else{
				
				return null;
			}
		}
		
		return null;
	}
}
